#!/usr/bin/env python3
"""
安装systemd服务的脚本
"""

import os
import shutil
import subprocess
import sys
from pathlib import Path

def install_systemd_service():
    """安装systemd服务"""
    print("🔧 安装Flask应用为systemd服务...")
    
    # 获取当前目录的绝对路径
    current_dir = Path(__file__).parent.absolute()
    service_file = current_dir / 'flask-education.service'
    
    if not service_file.exists():
        print("❌ 服务配置文件不存在")
        return False
    
    # 读取服务文件模板
    with open(service_file, 'r') as f:
        content = f.read()
    
    # 替换路径占位符
    content = content.replace('/path/to/your/education/backed', str(current_dir))
    
    # 创建临时服务文件
    temp_service_file = '/tmp/flask-education.service'
    with open(temp_service_file, 'w') as f:
        f.write(content)
    
    try:
        # 复制服务文件到systemd目录
        print("📋 复制服务文件到 /etc/systemd/system/...")
        subprocess.run(['sudo', 'cp', temp_service_file, '/etc/systemd/system/flask-education.service'], check=True)
        
        # 设置权限
        print("🔐 设置服务文件权限...")
        subprocess.run(['sudo', 'chmod', '644', '/etc/systemd/system/flask-education.service'], check=True)
        
        # 重载systemd
        print("🔄 重载systemd守护进程...")
        subprocess.run(['sudo', 'systemctl', 'daemon-reload'], check=True)
        
        # 启用服务
        print("⚡ 启用服务...")
        subprocess.run(['sudo', 'systemctl', 'enable', 'flask-education.service'], check=True)
        
        print("✅ systemd服务安装完成!")
        print("\n使用方法:")
        print("  启动服务: sudo systemctl start flask-education")
        print("  停止服务: sudo systemctl stop flask-education")
        print("  重启服务: sudo systemctl restart flask-education")
        print("  查看状态: sudo systemctl status flask-education")
        print("  查看日志: sudo journalctl -u flask-education -f")
        
        # 清理临时文件
        os.remove(temp_service_file)
        
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"❌ 安装失败: {e}")
        # 清理临时文件
        if os.path.exists(temp_service_file):
            os.remove(temp_service_file)
        return False
    except Exception as e:
        print(f"❌ 未知错误: {e}")
        return False

def uninstall_systemd_service():
    """卸载systemd服务"""
    print("🗑️  卸载Flask应用systemd服务...")
    
    try:
        # 停止服务
        print("🛑 停止服务...")
        subprocess.run(['sudo', 'systemctl', 'stop', 'flask-education.service'], check=False)
        
        # 禁用服务
        print("⛔ 禁用服务...")
        subprocess.run(['sudo', 'systemctl', 'disable', 'flask-education.service'], check=False)
        
        # 删除服务文件
        print("🗑️  删除服务文件...")
        subprocess.run(['sudo', 'rm', '/etc/systemd/system/flask-education.service'], check=True)
        
        # 重载systemd
        print("🔄 重载systemd守护进程...")
        subprocess.run(['sudo', 'systemctl', 'daemon-reload'], check=True)
        
        print("✅ systemd服务卸载完成!")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"❌ 卸载失败: {e}")
        return False

if __name__ == '__main__':
    if len(sys.argv) > 1:
        action = sys.argv[1]
        if action == 'uninstall':
            uninstall_systemd_service()
        elif action == 'install':
            install_systemd_service()
        else:
            print("用法: python install_service.py [install|uninstall]")
    else:
        install_systemd_service()
